//
//  YZYRealNameAuthenticationView.h
//  YZYSDKManagerDemo
//
//  Created by 赵隆杰 on 2024/6/7.
//

#import "YZYRealNameAuthenticationView.h"
#import "YZYSDKManagerHeader.h"
#import "YZYSaccountStore.h"
#import "ZCFunDataFormat.h"
#import "ZCNetworkManager.h"

@interface YZYRealNameAuthenticationView ()<UITextFieldDelegate>

@property (nonatomic, strong) UIButton *coverView;
@property (nonatomic ,strong) UITextField *name;
@property (nonatomic ,strong) UITextField *identityCard;
@property (nonatomic ,strong) UIButton *loginBtn;

@property (nonatomic ,strong) UITextField *firstResponderTextF;//记录将要编辑的输入框
@property (nonatomic, assign) CGFloat self_Height;//保存原始的view高度
@end

@implementation YZYRealNameAuthenticationView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        //监听键盘展示和隐藏的通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        
        UIImageView *backbg = [[UIImageView alloc] init];
        backbg.userInteractionEnabled = YES;
        backbg.backgroundColor = [UIColor whiteColor];
        backbg.layer.masksToBounds = YES;
        backbg.layer.cornerRadius = 4;
        [self addSubview:backbg];
        backbg.frame = CGRectMake(0, 0, popupW, popupH);
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont boldSystemFontOfSize:24];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.frame = CGRectMake(0, 15, backbg.frame.size.width, 25);
        titleLabel.text = @"实名认证";
        [backbg addSubview:titleLabel];
        
        UIButton *backBtn = [[UIButton alloc] init];
        backBtn.hidden = YES;
        [backbg addSubview:backBtn];
        backBtn.frame = CGRectMake(20, 0, 40, 40);
        [backBtn setTitle:@"跳过" forState:UIControlStateNormal];
        [backBtn setTitleColor:yzy_labelColor forState:UIControlStateNormal];
        backBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [backBtn addTarget:self action:@selector(didClickBackBtn) forControlEvents:UIControlEventTouchUpInside];
        
        UIView *nameView = [[UIView alloc] init];
        nameView.layer.masksToBounds = YES;
        nameView.layer.cornerRadius = 4;
        nameView.layer.borderColor = [UIColor colorWithRed:185/255.0 green:185/255.0 blue:185/255.0 alpha:1.0].CGColor;
        nameView.layer.borderWidth = 1;
        [backbg addSubview:nameView];
        nameView.frame = CGRectMake(25, CGRectGetMaxY(titleLabel.frame) + 20, backbg.frame.size.width - 50, 40);
        UIImageView *nameImage = [[UIImageView alloc] init];
        [nameView addSubview:nameImage];
        nameImage.image = [[YZYSaccountStore sharedInstance] getImage:@"realname"];
        nameImage.frame = CGRectMake(10, 10, 20, 20);
        self.name = [[UITextField alloc] init];
        self.name.placeholder = @"请输入姓名";
        self.name.delegate = self;
        self.name.font = [UIFont systemFontOfSize:16];
        self.name.returnKeyType = UIReturnKeyDone;
        [nameView addSubview:self.name];
        self.name.frame = CGRectMake(CGRectGetMaxX(nameImage.frame) + 10, 0, nameView.frame.size.width, nameView.frame.size.height);
        
        UIView *identityCardView = [[UIView alloc] init];
        identityCardView.layer.masksToBounds = YES;
        identityCardView.layer.cornerRadius = 4;
        identityCardView.layer.borderColor = [UIColor colorWithRed:185/255.0 green:185/255.0 blue:185/255.0 alpha:1.0].CGColor;
        identityCardView.layer.borderWidth = 1;
        [backbg addSubview:identityCardView];
        identityCardView.frame = CGRectMake(25, CGRectGetMaxY(nameView.frame) + 10, backbg.frame.size.width - 50, 40);
        UIImageView *identityCardImage = [[UIImageView alloc] init];
        [identityCardView addSubview:identityCardImage];
        identityCardImage.image = [[YZYSaccountStore sharedInstance] getImage:@"identity_card"];
        identityCardImage.frame = CGRectMake(10, 10, 20, 20);
        self.identityCard = [[UITextField alloc] init];
        self.identityCard.placeholder = @"请输入身份证号";
        self.identityCard.delegate = self;
        self.identityCard.font = [UIFont systemFontOfSize:16];
        self.identityCard.returnKeyType = UIReturnKeyDone;
        [identityCardView addSubview:self.identityCard];
        self.identityCard.frame = CGRectMake(CGRectGetMaxX(identityCardImage.frame) + 10, 0, identityCardView.frame.size.width, identityCardView.frame.size.height);
        
        self.loginBtn = [[UIButton alloc] init];
        self.loginBtn.layer.cornerRadius = 5;
        self.loginBtn.layer.masksToBounds = YES;
        self.loginBtn.backgroundColor = yzy_themeColor;
        self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.loginBtn setTitle:@"提  交" forState:UIControlStateNormal];
        [self.loginBtn addTarget:self action:@selector(didClickLogin) forControlEvents:UIControlEventTouchUpInside];
        [backbg addSubview:self.loginBtn];
        self.loginBtn.frame = CGRectMake(25, CGRectGetMaxY(identityCardView.frame) + 15, backbg.frame.size.width - 50, 40);
        
        UILabel *agreeLabel = [[UILabel alloc] init];
        agreeLabel.numberOfLines = 0;
        [backbg addSubview:agreeLabel];
        agreeLabel.frame = CGRectMake(20, CGRectGetMaxY(self.loginBtn.frame) + 10, backbg.frame.size.width - 40, 22);
        agreeLabel.text = @"为配合国家未成年人保护规定，同时保障您的合法权益，需要提交您的个人身份证信息用于实名认证，信息将会保密";
        agreeLabel.textColor = [UIColor colorWithRed:185/255.0 green:185/255.0 blue:185/255.0 alpha:1.0];
        agreeLabel.font = [UIFont systemFontOfSize:10];
        [agreeLabel sizeToFit];

    }
    return self;
    
}

- (void)didClickBackBtn {
    self.realNameAuthBlock(@NO);
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.coverView removeFromSuperview];
        [self removeFromSuperview];
    });
}

- (void)closeView {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.coverView removeFromSuperview];
        [self removeFromSuperview];
    });
}

- (void)didClickLogin {
    
    NSString *nameText = self.name.text;
    NSString *identityCardText = self.identityCard.text;
    
    if ([ZCFunDataFormat isBlankString:nameText]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"姓名为空"];
        return;
    }
    
    if ([ZCFunDataFormat isBlankString:identityCardText]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"身份证号码为空"];
        return;
    }
    
    NSDictionary *params = @{
        @"gameId": [ZCFunDataFormat GetPlatformGameID],
        @"userId": self.userId,
        @"identityCard": identityCardText,
        @"realName": nameText
    };
    [ZCNetworkManager postWithURL:YZY_AppendUrl(YZY_userRealIdCode) Params:params success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
        NSString *msg = [NSString stringWithFormat:@"%@",surperdic[@"msg"]];
        if ([surpercode isEqualToString:@"200"]) {
            msg = @"实名认证成功";
            self.realNameAuthBlock(@YES);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.coverView removeFromSuperview];
                [self removeFromSuperview];
            });
        }
        
    } failure:^(NSString *error) {
        
    }];
}

- (void)show {
    [[YZYSaccountStore sharedInstance] getCurrentWindowWithCompletion:^(UIWindow *window) {
        if (window) {
            UIButton *coverView = [[UIButton alloc] init];
            coverView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3f];
            [coverView addTarget:self action:@selector(coverViewClick) forControlEvents:UIControlEventTouchUpInside];
            self.coverView = coverView;
            coverView.frame = window.bounds;
            UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
            UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
            visualView.alpha = 0.0;
            [coverView addSubview:visualView];
            visualView.frame = coverView.frame;
            
            [window addSubview:coverView];
            
            self.frame = CGRectMake(0, 0, popupW, popupH);
            self.layer.cornerRadius = 12.0f;
            self.center = CGPointMake(window.center.x, window.center.y);
            if (![ZCFunDataFormat GetIsLandscape]) {
                self.center = CGPointMake(window.center.x, window.center.y - 40);
            }
            self.self_Height = self.frame.origin.y;
            [window addSubview:self];
        }
    }];
}

- (void)coverViewClick {
    [self endEditing:YES];
}

- (void)dealloc{
    //移除键盘通知监听者
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if ([self.firstResponderTextF isFirstResponder])[self.firstResponderTextF resignFirstResponder];
}
#pragma maek UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    self.firstResponderTextF = textField;//当将要开始编辑的时候，获取当前的textField
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark : UIKeyboardWillShowNotification/UIKeyboardWillHideNotification
- (void)keyboardWillShow:(NSNotification *)notification{
    CGRect rect = [self.firstResponderTextF.superview convertRect:self.firstResponderTextF.frame toView:self];//获取相对于self.view的位置
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];//获取弹出键盘的fame的value值
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self convertRect:keyboardRect fromView:self.window];//获取键盘相对于self.view的frame ，传window和传nil是一样的
    CGFloat keyboardTop = keyboardRect.origin.y;
    NSNumber * animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];//获取键盘弹出动画时间值
    NSTimeInterval animationDuration = [animationDurationValue doubleValue];
    if (keyboardTop < CGRectGetMaxY(rect)) {//如果键盘盖住了输入框
        CGFloat gap = keyboardTop - CGRectGetMaxY(rect) - 10;//计算需要网上移动的偏移量（输入框底部离键盘顶部为10的间距）
        __weak typeof(self)weakSelf = self;
        [UIView animateWithDuration:animationDuration animations:^{
            weakSelf.frame = CGRectMake(weakSelf.frame.origin.x, gap, weakSelf.frame.size.width, weakSelf.frame.size.height);
        }];
    }
    
}
- (void)keyboardWillHide:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSNumber * animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];//获取键盘隐藏动画时间值
    NSTimeInterval animationDuration = [animationDurationValue doubleValue];
    if (self.frame.origin.y < 0) {//如果有偏移，当影藏键盘的时候就复原
        __weak typeof(self)weakSelf = self;
        [UIView animateWithDuration:animationDuration animations:^{
            weakSelf.frame = CGRectMake(weakSelf.frame.origin.x, weakSelf.self_Height, weakSelf.frame.size.width, weakSelf.frame.size.height);
        }];
    }
}


@end
